﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCS.Core.Models;
using SCS.Core.Models.ModelsFontend;
using SCS.Core.ViewModels;
using SCSService;
using System.Xml;
using SCSInternetBanking;

namespace SCS.Core.Controllers
{
    public class TransferController : BaseFontendController
    {
       

        public ActionResult SaleMoney()
        {
            IntPage();
            return View();
        }

        public ActionResult BuyMoney()
        {
            IntPage();
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult SaleTransfer()
        {
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/SaleTransfer");
        }

        //[ChildActionOnly]
        //[HttpGet]
        //public ActionResult ResultFromNL()
        //{ 
        //    String transaction_info = Request.QueryString["transaction_info"];
        //    String order_code = Request.QueryString["order_code"];
        //    String payment_id = Request.QueryString["payment_id"];
        //    String payment_type = Request.QueryString["payment_type"];
        //    String secure_code = Request.QueryString["secure_code"];
        //    String price = Request.QueryString["price"];
        //    String error_text = Request.QueryString["error_text"];
        //    SCSInternetBanking.NganLuong.NL_Checkout nl = new SCSInternetBanking.NganLuong.NL_Checkout();
        //    bool check = nl.verifyPaymentUrl(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code);

        //    if (check)
        //    {
        //        //success
        //    }
        //    else
        //    { 
                
        //    }
        //}

        public JsonResult CheckAccountNameLiberty(string id)
        { 
            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            ShoppingCart cart=new ShoppingCart();
            List<Config_Payment_Method_Website> listMethod=new List<Config_Payment_Method_Website>();
            listMethod = cart.GetListPaymentMethod(siteGuid);

            var liberty=listMethod.Where(p=>p.MethodID==1).FirstOrDefault();

            SCSInternetBanking.LibertyReserve.ApiCredentials g_credentials = new SCSInternetBanking.LibertyReserve.ApiCredentials()
            {
                AccountNumber = liberty.AccountNumber,
                ApiName = liberty.ApiName,
                SecurityWord = liberty.SecurityWord
            };

            SCSInternetBanking.LibertyReserve.IApiAgent agent = SCSInternetBanking.LibertyReserve.ApiAgentFactory.Create(SCSInternetBanking.LibertyReserve.ApiProtocol.Xml, g_credentials);
            agent.RequireValidSslCertificate = true;
            string re = "-1";
            try
            {
               re = agent.AccountName(id) ?? "-1";
            }
            catch (Exception)
            {
                re = "-1"; 
            }
            
            return Json(re);
        }

        public JsonResult GetRateValueBymoney(string id)
        {
            var arr = id.Split(',');

            string res = "0";
            if (Models.ModelsFontend.ShoppingCart.GetRateValueBymoney(float.Parse(arr[0]), int.Parse(arr[1])) != null)
            {
                res = Models.ModelsFontend.ShoppingCart.GetRateValueBymoney(float.Parse(arr[0]), int.Parse(arr[1])).ToString();
            }
            else
            {
                res = "0";
            }

            return Json(res);
        }


        //public ActionResult CheckAccountNameNganLuong(string accountNo)
        //{ 
            
        //}

        [ChildActionOnly]
        [HttpGet]
        public ActionResult Buytransfers()
        {
            var viewModel = new BuyMoneyViewModels();
            viewModel.RateItems = Models.ModelsFontend.ShoppingCart.GetListRateByType(1);
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/Buytransfers", viewModel);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult Buytransfers(FormCollection collection)
        {
            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var cart = ShoppingCart.GetCart(this.HttpContext);
            int orderID = 0;
            int siteGuid = GetSiteGuid();
            SCSService.Invoice invoice = null;

            var viewModel = new ViewModels.BuyMoneyViewModels();
            TryUpdateModel(viewModel);

            if (viewModel.MethodBuy == "LR")
            {
                //// get Product liberty
                var product = ProductModel.GetProductByID(162); //162 là mua lierty ko được xóa

                cart.AddToCart(product);
            }
            else if (viewModel.MethodBuy == "WM")
            {
                //// get Product liberty
                var product = ProductModel.GetProductByID(162); //162 là mua lierty ko được xóa

                cart.AddToCart(product);
            }
           

            HttpCookie cookie = HttpContext.Request.Cookies["buyMoneyCookie"];
            var buyCollection = new Models.CollectionFontend.BuyCollection();

            Session["UserID"] = 60; //Vang lai

            if (cookie == null)
            {
                //cookie = new HttpCookie("invoice");
                if (Session["UserID"] != null)
                {
                   
                        Customer cus = ShoppingCart.GetCustomerByUserID(int.Parse(Session["UserID"].ToString()));

                        SCSService.UserService userSvc = new UserService();
                        Customer_Order cusOrder = new Customer_Order();
                        cusOrder.CreateDate = DateTime.Now;
                        cusOrder.CustomerID = cus.CustomerID;        //Luu ID cua khach hang sau khi dang nhap
                        cusOrder.Fullname = cus.CustomerName;
                        cusOrder.Phone = cus.Phone;
                        cusOrder.Email = cus.Email;
                        cusOrder.Address = cus.Address;
                        cusOrder.OrderStatus = 0;   //0 la Order start
                        cusOrder.Username = userSvc.GetUserByID(int.Parse(Session["UserID"].ToString())).UserName;  //User Name cua khach hang
                        cusOrder.SiteGuid = GetSiteGuid();

                        //Save Order
                        orderID = ShoppingCart.AddOrder(cusOrder);


                        //Process the order
                        // var cart = ShoppingCart.GetCart(this.HttpContext);
                        cart.CreateOrderTransfer(cusOrder, languageId);
                   
                }

                SCSService.BaseService baseSvc = new BaseService();
                //var ship = new Models.CollectionFontend.ShipmentCollection();

                Guid invoiceCode = Guid.NewGuid();

                //create Invoice
                invoice = new Invoice();
                invoice.OrderID = orderID;
                invoice.Status = 0;     //0 is status start payment
                invoice.CreateDate = DateTime.Now;
                invoice.CreateUser = int.Parse(Session["UserID"].ToString());       //checkout with ID login || ID of Customer Vang lai
                invoice.InvoiceCode = baseSvc.ConvertString(invoiceCode.ToString()).ToUpper();
                invoice.TotalPrice = cart.GetTotalValueCartItem(languageId);
                invoice.TotalProduct = cart.GetCountProductInOrder((int)orderID);
                invoice.PaymentDate = DateTime.Now;

                long invoiceID = ShoppingCart.CreateInvoice(invoice);               

                ////update tempOrderID for cart
                List<Cart> listCartItem = ShoppingCart.GetListCartItemByShoppingCartID(cart.shoppingCartId);
                foreach (var car in listCartItem)
                {
                    car.TempOrderID = orderID;
                    ShoppingCart.UpdateTempOrderIDforCart(car);
                }

                //Save to cookies for this transaction
                HttpCookie ck = new HttpCookie("buyMoneyCookie");
                ck.Value = invoice.InvoiceCode;
                ck.Expires = DateTime.Now.AddMinutes(30);//Thoi han luu cookie
                HttpContext.Response.Cookies.Add(ck);
            }
            else
            {
                //expires = DateTime.Parse(cookie.Value);
                //Đã tồn tại giao dịch ko tạo lại
                invoice = Models.ModelsFontend.ShoppingCart.GetInvoiceByInvoiCode(cookie.Value);

            }

            // Set up our ViewModel
            //var viewModel = new BuyMoneyViewModels
            //{
            //    CartItems = cart.GetListCartItemByCartID(),
            //    CartTotal = cart.GetTotalValueCartItem(languageId),
            //    Invoice = invoice
            //};
            //return PartialView("../BaseFontend/" + GetSiteGuid() + "/Buytransfers");

            if (viewModel.MethodTransferMoney == "NL") {

                string domain = "";
                string strs = Request.Url.PathAndQuery;
                if (Request.Url.Host == "localhost")
                {
                    domain = "localhost:3937";
                }
                else
                {
                    string host = this.Request.Url.Host;
                    if (host.Contains("www."))
                    {
                        host = host.Replace("www.", "");
                    }
                    domain = host;
                }

                String return_url = "http://" + domain + "/vi/Transfer/BuyMoneyResultForNL";// Địa chỉ trả về 
                String transaction_info = "";//Thông tin giao dịch
                String order_code = invoice.InvoiceCode;//Mã giỏ hàng 
                String receiver = "nguyenbahuong156@gmail.com"; //item.AccountNumber;//Tài khoản nhận tiền 
                String price = viewModel.ValueTransferMoney.ToString(); // total != null ? total.ToString() : "0";//Lấy giá của giỏ hàng
                SCSInternetBanking.NganLuong.NL_Checkout nl = new SCSInternetBanking.NganLuong.NL_Checkout();
                String url;
                url = nl.buildCheckoutUrl(return_url, receiver, transaction_info, order_code, price);

                ViewData["redirectStr"] = url;  
            }
            else if (viewModel.MethodTransferMoney == "BK") {
                 
                //String order_description = "";//Thông tin giao dịch
                //String order_id = invoices;//Mã giỏ hàng 
                //String bussiness = item.AccountNumber;//Tài khoản nhận tiền 
                //String total_amount = total != null ? total.ToString() : "0";//Lấy giá của giỏ hàng
                //String shipping_fee = "0";
                //String tax_fee = "0";
                //String url_success = "http://" + domain + "/vi/Checkout/PaymentOrderResult/1";
                //String url_cancel = "http://" + domain + "/vi/Checkout/PaymentOrderResult/2";
                //String url_detail = "";
                //SCSInternetBanking.BaoKim.BK_Checkout bk = new SCSInternetBanking.BaoKim.BK_Checkout();
                //String url;
                //url = bk.createRequestUrl(order_id, bussiness, total_amount, shipping_fee, tax_fee, order_description, url_success, url_cancel, url_detail);


            }
            return PartialView("../Commont/ResultOrder");
        }


        public ActionResult BuyMoneyResultForNL()
        {
            //Page return result form Ngan Luong
            IntPage();
            if (Request.Cookies["buyMoneyCookie"] != null)
            {
                HttpCookie myCookie = new HttpCookie("buyMoneyCookie");
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(myCookie);
            }
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult BuyMoneyResultsForNL()
        {
            //Method get (method received result from Ngan Luong)  
            //Only Ngan Luong
            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var cart = ShoppingCart.GetCart(this.HttpContext);
            Cart ca = ShoppingCart.GetCartByCartID(cart.shoppingCartId);
            int orderID = ca.TempOrderID ?? 0;
            int siteGuid = GetSiteGuid();
            string redirectStr = "";

            String transaction_info = Request.QueryString["transaction_info"];
            String order_code = Request.QueryString["order_code"];
            String payment_id = Request.QueryString["payment_id"];
            String payment_type = Request.QueryString["payment_type"];
            String secure_code = Request.QueryString["secure_code"];
            String price = Request.QueryString["price"];
            String error_text = Request.QueryString["error_text"];
            SCSInternetBanking.NganLuong.NL_Checkout nl = new SCSInternetBanking.NganLuong.NL_Checkout();
            bool check = nl.verifyPaymentUrl(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code);

            if (check)
            {

                Invoice invoice = ShoppingCart.GetInvoiceByOrderID(orderID);
                invoice.Status = invoice.Status;       //0 start; 1 success; 2 faild ; 3 send Order not payment online
                invoice.PaymentDate = DateTime.Now;
                //Update Status for Invoice
                ShoppingCart.UpdateInvoiceStatus(invoice);

                Customer_Order order = ShoppingCart.GetOrderByID(orderID);
                order.OrderStatus = invoice.Status;    //0 start; 1 success; 2 faild ; 3 send Order not payment online
                //Update Status for Order
                ShoppingCart.UpdateOrderStatus(order);

                //Create Payment
                Payment pay = new Payment();
                pay.InvoiceID = invoice.InvoiceID;
                pay.Status = 1;                         //1 success;2 transaction faild
                pay.Amount = invoice.TotalPrice;
                pay.CreateDate = DateTime.Now;

                int payId = ShoppingCart.CreatePayment(pay);

                //Send Invoice to Email

                
                //Payment success
                if (DefaultHostGetter().Contains("localhost"))
                {
                    //redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "1";
                }
                else
                {
                    //redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "1";
                }
            }
            else if (!check)
            {
                //Payment faild

                //Giao dịch lỗi
                Invoice invoice = ShoppingCart.GetInvoiceByOrderID(orderID);
                invoice.Status = 2;       //0 start; 1 success; 2 faild ; 3 send Order not payment online
                invoice.PaymentDate = DateTime.Now;
                //Update Status for Invoice
                ShoppingCart.UpdateInvoiceStatus(invoice);

                Customer_Order order = ShoppingCart.GetOrderByID(orderID);
                order.OrderStatus = 2;    //0 start; 1 success; 2 faild ; 3 send Order not payment online
                //Update Status for Order
                ShoppingCart.UpdateOrderStatus(order);

                //Create Payment
                Payment pay = new Payment();
                pay.InvoiceID = invoice.InvoiceID;
                pay.Status = 2;                         //1 success;2 transaction faild
                pay.Amount = invoice.TotalPrice;
                pay.CreateDate = DateTime.Now;

                int payId = ShoppingCart.CreatePayment(pay);

                if (DefaultHostGetter().Contains("localhost"))
                {
                    //redirectStr = "/" + siteGuid + "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "2";
                }
                else
                {
                    //redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrderConfirm/" + orderID + "," + "2";
                }

            }
            //empty cart
            cart.EmptyCart();

            if (Request.Cookies["buyMoneyCookie"] != null)
            {
                HttpCookie myCookie = new HttpCookie("buyMoneyCookie");
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(myCookie);
            }

            ViewData["redirectStr"] = redirectStr;
            return PartialView("../Commont/ResultOrder");
        }


    }
}
